from flask import Flask, request, send_file
from app.project.doc_to_recommendation.prdt_doc_to_rec_md import process
from app.project.doc_to_recommendation.utils.paths import DEFAULT_PATH
from app.project.doc_to_recommendation.utils.log_utils import get_logger
from app.project.doc_to_recommendation.utils.config_loader import load_config, get_config_path
from gevent import pywsgi
import sys

# 启动参数为环境名：sit1, t1, t2, prod 生产环境不传使用默认值即可
env = f"_{sys.argv[1]}" if len(sys.argv) > 1 else ""
CONFIG_FILE_NAME = f"http_ocr_layout{env}.yaml"
CONFIG_FILE_PATH = get_config_path(CONFIG_FILE_NAME)
config = load_config(CONFIG_FILE_PATH)

app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload_file():
    logger = get_logger(__name__)
    logger.info('Upload file received')
    if 'file' not in request.files:
        logger.info("No file received")
        return "No file received"
    file = request.files['file']
    if file.filename == '':
        logger.info("No file selected")
        return "No file selected"
    if file:
        filename = file.filename
        input_path = DEFAULT_PATH['_INPUT_PATH/']
        output_path = DEFAULT_PATH['_OUTPUT_PATH/']
        file_path = f'{input_path}/{filename}'
        file.save(file_path)
        logger.info("File:{} saved".format(filename))
        result = process(file_path, output_path, CONFIG_FILE_PATH)
        logger.info("doc process result:{}".format(result))
        if result:
            return send_file(f'{result}', as_attachment=True)
    return None

# @app.route('/test', methods=['GET'])
# def test():
#     return "Hello World"

if __name__ == '__main__':
    server = pywsgi.WSGIServer(('127.0.0.1', config.get("flask_port", 5000)), app)
    server.serve_forever()